package com.zs4sdk.activity.login;

import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ScrollView;

import com.common.library.data.CommonEventHandler;
import com.common.library.data.EventHandler2Get;
import com.common.library.listener.OnProcessListener;
import com.common.library.util.ActivityHelper;
import com.common.library.util.DialogUtils;
import com.common.library.util.EncryptHelper;
import com.common.library.util.HandlerUtil;
import com.common.library.util.Helper;
import com.common.library.util.ParamsHelper;
import com.common.library.widget.SDKGameUserListView;
import com.zs4gamesdk.R;
import com.zs4sdk.common.Extra;
import com.zs4sdk.entity.LoginJSONResultEntity;
import com.zs4sdk.entity.Zs4GameData;
import com.zs4sdk.receiver.SDKGameProcessReceiver;
import com.zs4sdk.statistics.Zs4GameStatistics;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Administrator on 2018/4/16.
 * 游客登录
 */

 class Zs4GameTouristLogin extends Zs4GameLoginBase {
    private Button btnGotoGame;
    private Button btnOtherAccount;
    private EditText etLoginMenu;
    private ViewStub stuLogin;
    ImageButton mIsHideUserList;
    SDKGameUserListView mUserListView;
    ScrollView mScrollerView;
    ArrayList<LoginJSONResultEntity> data_userlist;
    boolean isHideUserListStatus = true;
    private 	LoginJSONResultEntity mLastLonginEntity = null;
    private DialogUtils dialogUtils;

    // 模块回调
    private static HashMap<String, SDKGameProcessReceiver> mListenerList = new HashMap<String, SDKGameProcessReceiver>();
    public Zs4GameTouristLogin(Activity act, View view, Handler handler) {
        super(act, view, handler);
        data_userlist = Zs4GameData.getInstance().getUserInfoListOrderForUpdateTime();
        stuLogin = (ViewStub)mMainView.findViewById(R.id.stu_login);
        mLastLonginEntity = Zs4GameData.getInstance().getLastLoginedUserInfo();
    }
    protected  void initView(){
        if(!mIsInit){
            mIsInit = true;
        }
        LoginJSONResultEntity entity = Zs4GameData.getInstance().getLastLoginedUserInfo();
        Zs4GameData.getInstance().setLoginJSONResultEntity(entity);
        String loginName = Zs4GameData.getInstance().getLoginName();
        btnGotoGame = (Button)mMainView.findViewById(R.id.btn_zs4_game_goto_game);
        btnOtherAccount = (Button)mMainView.findViewById(R.id.btn_zs4_game_other_account_login);
        etLoginMenu = (EditText)mMainView.findViewById(R.id.zs4game_mAccountView_act_login_menu);
        mUserListView = (SDKGameUserListView)mMainView.findViewById(R.id.zs4game_mUserListView_act_login_menu);
        mScrollerView = (ScrollView)mMainView.findViewById(R.id.zs4game_mScrollerView_act_login_menu);
        mIsHideUserList = (ImageButton)mMainView.findViewById(R.id.zs4game_img_login_account_menu);
        etLoginMenu.setText(loginName);
        btnGotoGame.setOnClickListener(this);
        if(mOnClickListener != null){
            btnOtherAccount.setOnClickListener(mOnClickListener);
        }
        initUserList(data_userlist);
        mIsHideUserList.setOnClickListener(this);
        if (Helper.isNotEmpty(data_userlist)) {
            mIsHideUserList.setVisibility(View.VISIBLE);
            if(data_userlist.size() != 0){
                exchangeAccount((data_userlist.get(0)));
            }
        } else {
            mIsHideUserList.setVisibility(View.GONE);
        }

    }
    /**
     * function: 确认切换账号
     *
     * @param entity
     * @ author: aXiBa 2013-10-29 下午6:45:25
     */
    private void exchangeAccount(final LoginJSONResultEntity entity) {
        mLastLonginEntity = entity;
        if(entity == null){
            etLoginMenu.setText("");
            return;
        }
     //   String login_userId = Zs4GameData.getInstance().getUserId();
    //    String loginKey = Zs4GameData.getInstance().getLoginKey();
        // 已经登录
        if(!entity.getMobile().isEmpty()){
            etLoginMenu.setText(entity.getMobile());
        }else {
            etLoginMenu.setText(entity.getLoginname());
        }

        //  ScrollView mScrollerView = findView(ScrollView.class, ActivityHelper.getIdResId("zs4gameviewid_mScrollerView_act_login_menu"));
        if (Helper.isNotNull(mScrollerView)) {
            mScrollerView.scrollTo(0, 0);
        }
       // mLoginInfo = entity;
    }
    // 用户信息列表
    private void initUserList(final ArrayList<LoginJSONResultEntity> data) {
        mUserListView.init(data,
                new SDKGameUserListView.ItemHandler() {

                    @Override
                    public void onItemClick(int pos) {
                      //  HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.COMFIRM_EXCHANGEACCOUNT, (LoginJSONResultEntity) mUserListView.getItem(pos));
                       // loginInputPasswordEditText.setText("");
                        exchangeAccount((LoginJSONResultEntity)mUserListView.getItem(pos));
                        mScrollerView.setVisibility(View.GONE);
                        isHideUserListStatus = true;
                    }

                    @Override
                    public void deleteItem(int pos) {
                       // HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.COMFIRM_DELETEACCOUNT, (LoginJSONResultEntity) mUserListView.getItem(pos));
                        LoginJSONResultEntity entity = (LoginJSONResultEntity) mUserListView.getItem(pos);
                        deleteAccount(entity);

                    }
                });

    }
    /**
     * function: 确认删除账号
     *
     * @param entity
     * @ author: aXiBa 2013-10-29 下午6:45:25
     */
    private void deleteAccount(final LoginJSONResultEntity entity) {

        String content = String.format(ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_hint_comfirm_deleteaccount")),
                (Helper.isEmpty(entity.getMobile()) ? entity.getLoginname() : entity.getMobile()));
        if (Helper.isNotNull(entity)) {

            dialogUtils = new DialogUtils(mActivity,
                    content,
                    ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_btn_confirm")),
                    ActivityHelper.getString(ActivityHelper.getStringResId("zs4gamestring_btn_cancel")),
                    new DialogUtils.LeaveDialogListener() {
                        @Override
                        public void onClick(View view) {
                            int id = view.getId();
                            if (ActivityHelper.getIdResId("zs4gameviewid_dialog_btn_cannel") == id) {
                                dialogUtils.dismiss();
                            }
                            //确定
                            if (ActivityHelper.getIdResId("zs4gameviewid_dialog_btn_sure") == id) {
                                HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.SHOWPROCESS_FORACTIVITY);
                                deleteAccountHandler(entity);
                                HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.DISMISSPROCESS_FORACTIVITY);
                                exchangeAccount((LoginJSONResultEntity)mUserListView.getItem(0));
                                dialogUtils.dismiss();
                            }
                        }
                    });
            dialogUtils.show();

        }
    }


    /**
     * function: 删除账号处理
     *
     * @param entity
     * @ author: aXiBa 2013-12-5 下午2:58:34
     */
    public void deleteAccountHandler(LoginJSONResultEntity entity) {


        if (Helper.isNotEmpty(data_userlist) && Helper.isNotNull(entity)) {

            for (int i = 0; i < data_userlist.size(); i++) {
                LoginJSONResultEntity curEntity = data_userlist.get(i);
                if (Helper.isNotNull(curEntity) && entity.getUserId().equals(curEntity.getUserId())) {

                    // 删除数据
                    data_userlist.remove(i);
                    Zs4GameData.getInstance().deleteAccount(entity);
                    String editStr = etLoginMenu.getText().toString();
                    if(!entity.getMobile().isEmpty()){
                        if(editStr.equals(entity.getMobile())){
                            etLoginMenu.setText("");
                        }
                    }else {
                        if(editStr.equals(entity.getLoginname())){
                            etLoginMenu.setText("");
                        }
                    }
                    // 重新初始化账号列表

                    if(!Helper.isNotEmpty(data_userlist)){
                        mScrollerView.setVisibility(View.GONE);
                        isHideUserListStatus = true;
                    }
                    initUserList(data_userlist);

                    break;
                }
            }
            LoginJSONResultEntity lastLoginedUserInfoEntity = Zs4GameData.getInstance().getLastLoginedUserInfo();
            if(lastLoginedUserInfoEntity != null){
                String userId = entity.getUserId();
                String lastUseId = lastLoginedUserInfoEntity.getUserId();
                if(userId.equals(lastUseId)){
                    Zs4GameData.getInstance().clearLastLoginUserInfo();
                }
            }
        }
    }
    @Override
    public void login() {
        touristLogin();
    }
    /**
     * function: 注册广播
     *
     * @param action
     * @param listener
     * @ author: aXiBa 2013-3-18 下午2:46:31
     */
    private void registerReceiver(String action, OnProcessListener listener) {

        if (!mListenerList.containsKey(action)) {
            SDKGameProcessReceiver receiver = new SDKGameProcessReceiver(action, listener);
            IntentFilter filter = new IntentFilter();
            filter.addAction(action);

            ActivityHelper.getGlobalApplicationContext().registerReceiver(receiver, filter);
            mListenerList.put(action, receiver);
        }
    }

    @Override
    protected void show() {
        stuLogin.setVisibility(View.VISIBLE);
    }

    @Override
    protected void hide() {
        stuLogin.setVisibility(View.GONE);
    }
    @Override
    public void doOnClick(View v) {
        int id = v.getId();
        if(id == R.id.btn_zs4_game_goto_game){
            login();
        }else if(id == R.id.zs4game_img_login_account_menu){
            if (Helper.isNotNull(mScrollerView)) {
                mScrollerView.scrollTo(0, 0);
            }
            // 如果是隐藏状态就打开，显示状态就关闭
            if (isHideUserListStatus) {

                if (data_userlist.size() == 0) {
                    ActivityHelper.showLongToast(ActivityHelper.getStringResId("zs4gamestring_hint_other_user_empty"));
                    return;
                }

                mScrollerView.setVisibility(View.VISIBLE);

                TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
                mShowAction.setDuration(500);
                mUserListView.startAnimation(mShowAction);
                isHideUserListStatus = false;
            } else {
                mScrollerView.setVisibility(View.GONE);
                isHideUserListStatus = true;
            }

        }
    }
    /**
     * function: 游客登录
     *
     * @ author: aXiBa 2013-4-15 下午4:08:56
     */
    public void touristLogin() {

        // 注册登录广播接收
        final String action = mActivity.getPackageName().concat(Extra.ACTIONKEY.LOGIN_POSTFIX);
        if (isNetworkAvailable()) {
            doRequestRegisterGuest(action);
        } else {
            ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
            HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.DISMISSPROCESS);
            return;
        }
    }
    /**
     * 游客登录,用游客id登录
     */
    private void doRequestRegisterGuest(final String action) {

        if(mLastLonginEntity == null){
            ActivityHelper.showLongToast(mActivity,mActivity.getString(R.string.zs4game_account_no_null));
            return;
        }
        HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.SHOWPROCESS_FORACTIVITY, mActivity);
        ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
        String url =   Extra.URL.IDLOGINURL;

        final String account = mLastLonginEntity.getUserId();
        final String password = EncryptHelper.encryptByAES(EncryptHelper.md5(mLastLonginEntity.getUserId()));
        paramList.add(new BasicNameValuePair("user_id", EncryptHelper.encryptByAES(account)));
        paramList.add(new BasicNameValuePair("password", password));
        new EventHandler2Get(
                url,
                paramList,
                ParamsHelper.getUserAgent1(),
                new CommonEventHandler.ResultHandlerInEvent() {

                    @Override
                    public void doResultHanler(JSONObject result) throws JSONException {
                        Log.e("login"," login result is "+result.toString());
                        HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.DISMISSPROCESS_FORACTIVITY);
                        Message msg = mLoginHandler.obtainMessage();
                        msg.what = Extra.MessageKey.REQUESTCOMPLETE_LASTLOGINACCOUNT;
                        msg.obj = mActivity;
                        Bundle bundle = new Bundle();
                        bundle.putString("param1", action);
                        bundle.putString("param2", result.toString());
                        bundle.putString("login_type", LOGINTYPE_EXCHANGE);
                        bundle.putString("account", account);
                        bundle.putString("password", password);
                        msg.setData(bundle);
                        // 发送消息
                        mLoginHandler.sendMessage(msg);
                    }

                    @Override
                    public void doExceptionHandler() {
                        HandlerUtil.sendMessage(mLoginHandler, Extra.MessageKey.DISMISSPROCESS_FORACTIVITY);
                        //sendErrorMessage(mActivity, action);
                    }
                });
    }
    public void handleResult(Bundle bundle){
        final Context ctx = mActivity;
        String action = "";
        String jsonResult = "";
        String type = "";
        String account = "";
        String password = "";
        if (null != bundle) {
            action = bundle.getString("param1");
            jsonResult = bundle.getString("param2");
            type = bundle.getString("login_type");
            account = bundle.getString("account");
            password = bundle.getString("password");
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(jsonResult);
            loginSuccess(mActivity,type,jsonObject,account,password);
            String userId = jsonObject.optString(LoginJSONResultEntity.COLUMN_USERID);
            Zs4GameStatistics.setLoginSuccessBusiness(userId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }



}
